/**
 * 存储适配器基类
 * 简化版本，提供基础功能
 */

import { IStorageAdapter, IStorageConfig, IUploadOptions, IUploadResult } from './interfaces';
import { createLogger, ILogger } from '../../utils/logger';

/**
 * 存储适配器基类
 */
export abstract class BaseStorageAdapter implements IStorageAdapter {
  public readonly name: string;
  protected logger: ILogger;
  protected _initialized = false;
  protected config: IStorageConfig;

  constructor(name: string, config: IStorageConfig = {}) {
    this.name = name;
    this.config = config;
    this.logger = createLogger(`Storage:${name}`);
  }

  get initialized(): boolean {
    return this._initialized;
  }

  /**
   * 确保适配器已初始化
   */
  protected ensureInitialized(): void {
    if (!this._initialized) {
      throw new Error(`Storage adapter ${this.name} is not initialized`);
    }
  }

  /**
   * 标记为已初始化
   */
  protected markAsInitialized(): void {
    this._initialized = true;
  }

  /**
   * 生成文件ID
   */
  protected generateFileId(filename?: string): string {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2);
    const extension = filename ? this.getFileExtension(filename) : '';
    return `${timestamp}_${random}${extension}`;
  }

  /**
   * 获取文件扩展名
   */
  protected getFileExtension(filename: string): string {
    const lastDot = filename.lastIndexOf('.');
    return lastDot > 0 ? filename.substring(lastDot) : '';
  }

  /**
   * 获取文件MIME类型
   */
  protected getMimeType(file: File | Blob | Buffer): string {
    if (file instanceof File) {
      return file.type || 'application/octet-stream';
    }
    if (file instanceof Blob) {
      return file.type || 'application/octet-stream';
    }
    return 'application/octet-stream';
  }

  /**
   * 获取文件大小
   */
  protected getFileSize(file: File | Blob | Buffer): number {
    if (file instanceof File || file instanceof Blob) {
      return file.size;
    }
    if (Buffer.isBuffer(file)) {
      return file.length;
    }
    return 0;
  }

  /**
   * 检查是否为图片文件
   */
  protected isImageFile(mimeType: string): boolean {
    return mimeType.startsWith('image/');
  }

  /**
   * 获取图片尺寸（如果是图片文件）
   */
  protected async getImageDimensions(file: File | Blob): Promise<{ width: number; height: number } | undefined> {
    if (!this.isImageFile(this.getMimeType(file))) {
      return undefined;
    }

    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => {
        resolve({ width: img.width, height: img.height });
        URL.revokeObjectURL(img.src);
      };
      img.onerror = () => {
        resolve(undefined);
      };
      img.src = URL.createObjectURL(file as Blob);
    });
  }

  // 抽象方法，由子类实现
  abstract initialize(config?: IStorageConfig): Promise<void>;
  abstract upload(file: File | Blob | Buffer, options?: IUploadOptions): Promise<IUploadResult>;
  abstract delete(id: string): Promise<void>;
  abstract exists(id: string): Promise<boolean>;
  abstract getInfo(id: string): Promise<IUploadResult>;
  abstract destroy(): Promise<void>;
}
